package org.yidu.spider.controller;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Value("${rule.path}")
    private String rulesPath = "/data/rules/";

    private String[] getRulesFileList() {

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = user.getUsername(); // get logged in username
        String[] files = new File(rulesPath + userName + "/").list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".xml")) {
                    return true;
                }
                return false;
            }
        });
        return files;
    }

    /**
     * 采集规则一览页面
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String ruleList(Map<String, Object> model) {
        logger.info("ruleList has bean called.");
        // 查询规则文件夹下的所有规则文件， 列出来
        model.put("files", getRulesFileList());
        return "index";
    }

}